import datetime

from absl import app, flags
import pandas as pd
import memcache

from xunkemgmt_client.tool.slack_noti import send_to_slack
from coin.base.query_util import query_transfer_histories
from google.protobuf.json_format import MessageToDict

FLAGS = flags.FLAGS


class MemcacheDB(object):
  def __init__(self):
    self._mc = memcache.Client(["127.0.0.1:11211"])

  def get_value(self, key):
    value_str = self._mc.get(key)
    return value_str

  def set_value(self, key, value):
    self._mc.set(key, value, time=86400)


def main(_):
  pd.set_option('display.width', 1000)
  pd.set_option('display.max_rows', None)
  pd.set_option('display.max_columns', None)
  pd.set_option('max_colwidth', 200)

  response_list = query_transfer_histories(end_time=datetime.datetime.now(),
                      start_time=datetime.datetime.now() - \
                      datetime.timedelta(days=FLAGS.interval_in_days))
  transfer_list = []
  for acct_transfer_bundle in response_list:
    acct = MessageToDict(acct_transfer_bundle.account_request,
                         preserving_proto_field_name=True)
    for transfer in acct_transfer_bundle.each_transfer:
      acct_transfer = {**acct, **MessageToDict(transfer,
                      preserving_proto_field_name=True)}
      transfer_list.append(acct_transfer)
  transfer_df = pd.DataFrame(transfer_list)
  transfer_df = transfer_df[
    transfer_df['type'].str.upper().isin(('WITHDRAW', 'DEPOSIT'))]
  
  if len(transfer_df) ==  0:
    return

  transfer_df.rename({'transfer_id': 'transfer_hid'}, axis=1, inplace=True)
  transfer_df.sort_values(by=['transfer_hid'], inplace=True)
  transfer_df['transfer_hid'] = transfer_df['transfer_hid'].astype('int64')
  transfer_df['qty'] = transfer_df['qty'].apply(lambda x: "{:,.2f}".format(x))
  transfer_df['account_id'] = transfer_df.apply(lambda x: x['from_account'].get('account_id', '')
      if 'from_account' in transfer_df.columns and pd.notnull(x['from_account'])
      else x['to_account'].get('account_id', ''), axis=1)
  account_info_columns = ['account_id', 'market_type', 'exchange', 'owner']
  transfer_info_columns = [
      'transfer_time',
      'currency',
      'from_address',
      'to_address',
      'qty',
      'type',
      'external_transfer_id',
      'status'
  ]
  transfer_df['currency'] = transfer_df['currency'].str.upper()
  transfer_df['transfer_time'] = transfer_df['create_timestamp'].apply(lambda x: 
    datetime.datetime.utcfromtimestamp(int(x) / 10**9).strftime('%Y%m%d %H:%M:%S'))
  transfer_df = transfer_df.fillna('')
  transfer_df.set_index('transfer_hid', inplace=True)
  transfer_df = transfer_df[account_info_columns + transfer_info_columns]
  transfer_df.sort_values(['transfer_time'], inplace=True)

  memdb = MemcacheDB()
  key = 'max_transfer_hid'
  max_hid = max(transfer_df.index.tolist())
  max_hid_mem = memdb.get_value(key)
  memdb.set_value(key, max_hid)
  if max_hid_mem is None:
    return
  if FLAGS.send_to_slack:
    max_hid_mem = int(max_hid_mem)
    if max_hid > max_hid_mem:
      transfer_send = transfer_df.loc[transfer_df.index > max_hid_mem]
      msg = "```" + str(transfer_send) + "```"
      send_to_slack(msg, 'coin_transfer_noti', 'msg')

if __name__ == '__main__':
  flags.DEFINE_boolean('send_to_slack', False, 'send to slack')
  flags.DEFINE_integer('interval_in_days', 14, 'transfer history query interval')

  app.run(main)
